from flask import Flask, request, g
from flask_sockets import Sockets
import json
import datetime

app = Flask(__name__)
sockets = Sockets(app)

from flask_cors import *
CORS(app, supports_credentials=True)

msg_list = [{"kefu": "你好，有什么可以帮助您！", "type": "kefu"}]


@sockets.route('/echo')
def echo_socket(ws):
    print("hello")
    ws.send(json.dumps(msg_list))
    while not ws.closed:
        msg = ws.receive()
        print(msg)
        if msg:
            data = json.loads(msg)
            print(data, type(data))
            data['id'] = 1
            msg_list.append(data)
            now = datetime.datetime.now().isoformat()
            print(type(msg_list))
            ws.send(json.dumps(msg_list))  #发送数据

# 发送消息
@sockets.route('/send')
def ws_socket(ws):
    # 获取消息
    msg = request.args.get('msg')
    ws.send(msg)


@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    print('server start')
    server.serve_forever()
